//
//  ZCMainVC.m
//  zctx
//
//  Created by ZhengDarren on 15/9/28.
//  Copyright © 2015年 sanliang. All rights reserved.
//
#import "ZCLoginVC.h"
#import "ZCMainVC.h"
#import "ZCXActivityVC.h"

#import "ZCMainHeader.h"

@interface ZCMainVC ()<UITableViewDataSource,UITableViewDelegate,ZCUnqualifiedCellDelegate,ZCFreeCellDelegate,UIsharePopoverListViewDelegate,ZCHotTitleCellDelegate>
{
    NSMutableArray *mainArray;
    NSMutableArray *dataArray;
    NSMutableArray *adArray;
    NSMutableArray *tagsArray;
    NSMutableArray *newsArray;
    AdView *adView;
    BOOL isconn;
}
@property (nonatomic,assign)NSInteger offset;
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic, strong) Reachability *conn;
@property (nonatomic,strong) NSString *rank;

@property (nonatomic,strong)NSString *rankStr;
@end

@implementation ZCMainVC

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"ZCMainVC"];
    [MTA trackPageViewBegin:@"ZCMainVC"];
    self.tabBarController.hidesBottomBarWhenPushed = NO;
    [self.navigationController setNavigationBarHidden:NO];
    
    [ZCTool gotoAppStore];//评分弹层
    [self requestAds];//广告
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"ZCMainVC"];
    [MTA trackPageViewEnd:@"ZCMainVC"];
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    _offset = 0;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkState) name:kReachabilityChangedNotification object:nil];
    self.conn = [Reachability reachabilityForInternetConnection];
    [self.conn startNotifier];
    [self initnavegation];
    [self mainScanshow];
    mainArray = [NSMutableArray array];
    dataArray = [NSMutableArray array];
    adArray = [NSMutableArray array];
    tagsArray = [NSMutableArray array];
    newsArray = [NSMutableArray array];
    self.rank = @"0";
    self.rankStr = @"0";
    if (!UserModel.mid) {
        [UserModel setMid:@"0"];
        [UserModel setPassword:@"0"];
    }

    [self initTableView]; //初始化UITableView
    [self showfriendView];//推荐给盆友
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCHotinformationCell" bundle:nil] forCellReuseIdentifier:@"hotcell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCFreeCell" bundle:nil] forCellReuseIdentifier:@"freesCell"];
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)])
    {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])
    {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
  
    self.tableView.mj_header = [MJDIYHeader headerWithRefreshingBlock:^{
        _offset = 0;
        [self initNewsData];//热点资讯
    }];
    [self.tableView.mj_header beginRefreshing];
}
#pragma mark 扫一扫引导
-(void)mainScanshow{
    //扫一扫引导
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstStartT"]){
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstStartT"];
        ZCGuideView * zcview = [[ZCGuideView alloc]initWithFrame:[UIScreen mainScreen].bounds andType:ZCGuideViewTypeSao];
        [zcview show];
    }
}


#pragma mark 请求广告
-(void)requestAds{
    [NetworkManager requestIndexadlistsWithMid:UserModel.mid password:UserModel.password success:^(NSDictionary *dictResponse) {
        if ([[dictResponse objectForKey:@"content"]isKindOfClass:[NSArray class]]) {
            NSArray *array =(NSArray *)[dictResponse objectForKey:@"content"];
            if (array.count>0) {
                adArray = [array mutableCopy];
                [self.tableView reloadData];
            }
        }
    } failure:^(NSError *error) {
        
    }];
}

#pragma mark 请求首页标签
-(void)requestTags{
    [NetworkManager requestIndextagsWithsuccess:^(NSDictionary *dictResponse) {
        tagsArray = (NSMutableArray *)[dictResponse objectForKey:@"content"];
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:0];
        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
    } failure:^(NSError *error) {
        
    }];
    
}

#pragma mark 请求首页热点资讯
-(void)initNewsData{
    if (_offset==0) {
        [newsArray removeAllObjects];
    }
    [NetworkManager requestIndexlatestnewsWithPagecount:[NSString stringWithFormat:@"%ld",(long)_offset] rank_type:self.rank  success:^(NSDictionary *dictResponse) {
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        NSMutableArray *dataRR  = (NSMutableArray *)[dictResponse objectForKey:@"content"];
        if ([dataRR isKindOfClass:[NSMutableArray class]]){
            self.tableView.mj_footer = [MJDIYFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
            if (dataRR !=nil && ![dataRR isKindOfClass:[NSNull class]] &&dataRR.count !=0){
                [newsArray addObjectsFromArray:dataRR];
                [self.tableView reloadData];
            }
        }else{
            // 拿到当前的上拉刷新控件，变为没有更多数据的状态
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}

#pragma mark 请求首页数据
-(void)requestMaindata{
    
    NSLog(@"userModel.mid = %@ , userModel.password = %@",UserModel.mid,UserModel.password);
    [NetworkManager requestFoundingGetLatestWithMid:UserModel.mid password:UserModel.password success:^(NSDictionary *dictResponse) {
        dataArray = (NSMutableArray *)[dictResponse objectForKey:@"content"];
        
    } failure:^(NSError *error) {
        
    }];
}

#pragma mark 加载更多
-(void)loadMoreData{
    //上拉加载
    _offset = _offset+1;
    [self initNewsData];
}

-(void)initTableView{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [[UIView alloc]init];
    self.tableView.sectionFooterHeight = 0.0001;
    self.tableView.backgroundColor = [UIColor colorWithHexString:@"#fafcfb"];
    self.tableView.separatorColor = RGB(236, 237, 238);
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0,0,0));
    }];
}

#pragma mark UITableViewDataSource,UITableViewDelegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0) {
        return 1;
    }else if(section==1){
        return 1;
    }else if(section==2){
        return 1;
    }else{
        return newsArray.count;
    }

}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        static NSString *cellIndentifier = @"freesCell";
        ZCFreeCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
        if (cell == nil) {
            cell = [[ZCFreeCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
        }
        cell.delegate = self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else if (indexPath.section==1){
        static NSString *caellid =@"unqualcell";
        ZCUnqualifiedCell *cell = [tableView dequeueReusableCellWithIdentifier:caellid];
        if (cell == nil) {
            cell = [[ZCUnqualifiedCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:caellid];
        }
        cell.delegate = self;
        return cell;
    }else if(indexPath.section ==2){
        static NSString *celid =@"cell";
        ZCHotTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:celid];
        if (cell == nil) {
            cell = [[ZCHotTitleCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:celid];
        }
        cell.delegate =self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if ([self.rank isEqualToString:@"0"]) {
            cell.segmented.selectedSegmentIndex = 0;
        }else{
            cell.segmented.selectedSegmentIndex = 1;
        }
        return cell;
    }else{
        static NSString *caellid =@"hotcell";
        ZCHotinformationCell *cell = [tableView dequeueReusableCellWithIdentifier:caellid];
        if (cell == nil) {
            cell = [[ZCHotinformationCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:caellid];
        }
        if (newsArray.count>0) {
            NSDictionary *dict = newsArray[indexPath.row];
            cell.newsDict = dict;

        }
        return cell;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        return 157;
    }else if (indexPath.section==1){
        return 83;
    }else if(indexPath.section==2){
        return 44;
    }else{
        return 77;
    }
    return 50;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return 130;
    }else if(section==3){
        return 0.0001;
    }else{
        return 4;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0001;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==3) {

        NSDictionary *moel =newsArray[indexPath.row];
        ZCinformationVC *vc = [[ZCinformationVC alloc] init];
        vc.strURL = [NSString stringWithFormat:@"%@",[moel objectForKey:@"url"]];;
        vc.title = [NSString stringWithFormat:@"食品安全资讯"];
        vc.urlID = [NSString stringWithFormat:@"%@",[moel objectForKey:@"id"]];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (indexPath.section==1) {
        ZCSearchVC *vc = [[ZCSearchVC alloc]init];
        vc.isbao = @"1";
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
    [self performSelector:@selector(unselectCell:) withObject:nil afterDelay:0.3];
}

-(void)unselectCell:(id)sender{
    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView = [[UIView alloc]init];
    if (section==0) {
        headView.frame =CGRectMake(0, 0, SCREEN_WIDTH, ADViewHEIGHT);
        NSMutableArray *imageURLs = [NSMutableArray array];
        for (NSDictionary *imageDic in adArray) {
            NSString *urlstr = [NSString stringWithFormat:@"%@%@",[NetworkManager strURLBasic],[imageDic objectForKey:@"img"]];
            [imageURLs addObject:urlstr];
        }
        adView = [AdView adScrollViewWithFrame:CGRectMake(0,-1, SCREEN_WIDTH, ADViewHEIGHT+1)  \
                                  imageLinkURL:imageURLs\
                           placeHoderImageName:@"placeHoder.jpg" \
                          pageControlShowStyle:UIPageControlShowStyleCenter];
        __block ZCMainVC *weakSelf = self;
        //图片被点击后回调的方法
        adView.callBack = ^(NSInteger index,NSString * imageURL)
        {
            NSLog(@"被点中图片的索引:%ld---地址:%@",(long)index,imageURL);
            NSDictionary *model =(NSDictionary *)weakSelf->adArray[index];
            NSLog(@"model =%@",model);
            NSString *type = [NSString stringWithFormat:@"%@",[model objectForKey:@"type"]];
            NSString *state = [NSString stringWithFormat:@"%@",[model objectForKey:@"fd_state"]];
            NSString *fdid = [NSString stringWithFormat:@"%@",[model objectForKey:@"fdid"]];
            
            if ([type isEqualToString:@"0"]) {
                
                if ([state isEqualToString:@"0"])
                { // 0 审核中 1众筹中 2 抽样中 3完成 4 异常
                    
                    ZCMeAuditDetailsVC *vc = [[ZCMeAuditDetailsVC alloc]init];
                    vc.pid =fdid;
                    vc.hidesBottomBarWhenPushed = YES;
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                }else if ([state isEqualToString:@"1"]){
                    ZCInvolvedDetailsVC *vc = [[ZCInvolvedDetailsVC alloc]init];
                    vc.pid =fdid;
                    vc.hidesBottomBarWhenPushed = YES;
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                }else if ([state isEqualToString:@"2"]){
                    ZCSamplingDetailVC *vc = [[ZCSamplingDetailVC alloc]init];
                    vc.pid =fdid;
                    vc.hidesBottomBarWhenPushed = YES;
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                }else if ([state isEqualToString:@"3"]){
                    ZCProjectdetailsVC *vc = [[ZCProjectdetailsVC alloc]init];
                    vc.pid =fdid;
                    vc.hidesBottomBarWhenPushed = YES;
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                }
            }else{
                //url 广告
                NSString *url = [NSString stringWithFormat:@"%@",[model objectForKey:@"url"]];
                NSString *title = [NSString stringWithFormat:@"%@",[model objectForKey:@"title"]];
                NSString *activity = [NSString stringWithFormat:@"%@",[model objectForKey:@"ifenter_activity"]];
                [weakSelf useNStringjudge:url andTitle:title andactivity:activity]; //判断url 类型
            }
        };
        [headView addSubview:adView];
        return headView;
    }else{
        headView.frame =CGRectMake(0, 0, SCREEN_WIDTH, 4);
        return headView;
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)])
    {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

#pragma mark 食事周刊 有害曝光
-(void)UnqualifiedCellClick:(NSInteger)index{
    if (index==0) {
        ZCeatweeklyVC *eatvc = [[ZCeatweeklyVC alloc]init];
        eatvc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:eatvc animated:YES];
    }else{
        ZCSearchVC *vc = [[ZCSearchVC alloc]init];
        vc.isbao = @"1";
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
}


#pragma mark 四个按钮点击
-(void)didSelectDiscountIndex:(NSInteger )index{
    NSLog(@"Discountcell - index =%ld",(long)index);
    theAppdelegate.tabbarIndex = @"0";
    if (index==0) {
        [self searchButtonPressed];
    }else if (index==1){
        ZCSamplingVC *samVC = [[ZCSamplingVC alloc]init];
        samVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:samVC animated:YES];
    }else if(index==2) {
        if (UserModel.password.length>1) {
            ZCRaiseVC *vc = [[ZCRaiseVC alloc] init];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            ZCLoginVC *login = [[ZCLoginVC alloc]init];
            login.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:login animated:YES];
        }
    }else{
        ZCInvolvedVC *involve = [[ZCInvolvedVC alloc]init];
        involve.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:involve animated:YES];
    }
}

#pragma mark 查一查
-(void)searchButtonPressed{
    ZCHotTagsVC *vc = [[ZCHotTagsVC alloc]init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark 推荐给朋友
-(void)showfriendView{
    
    ZCFriendView *friendView = [[ZCFriendView alloc]initWithFrame:CGRectZero];
    friendView.friendBlock = ^(void){
        ActionView *action = [[ActionView alloc]initWithFrame:CGRectZero];
        action.isweb =6;
        [action showInView:self.view];
    };
    [self.view addSubview:friendView];
    
}

#pragma mark 时间、热度
-(void)SelectHottitleCell:(NSInteger)index
{
    self.rankStr = self.rank;
    if (index==0) {
        self.rank = @"0";
        _offset = 0;
    }else{
        self.rank = @"1";
        _offset = 0;
    }
    
    if ([self.rankStr isEqualToString:self.rank]) {
        
    }else{
        [newsArray removeAllObjects];
    }
    [self initNewsData];
}

#pragma mark 分享
-(void)shareButtonPressed{
    CGFloat xWidth = SCREEN_WIDTH - 60.0f;
    CGFloat yHeight = xWidth;
    payShareView *poplistview = [[payShareView alloc] initWithFrame:CGRectMake(0,0, xWidth, yHeight)];
    [poplistview show];
}
- (void)popoverListView:(UIsharePopoverListView *)popoverListView
     didSelectIndexPath:(NSIndexPath *)indexPath{
    
    [NetworkManager  requestGetMyshareWithMid:UserModel.mid password:UserModel.password success:^(NSDictionary *dictResponse) {
        NSLog(@"dict = %@",dictResponse);
        WXMediaMessage *message = [WXMediaMessage message];
         message.title = [NSString stringWithFormat:@"%@",[dictResponse objectForKey:@"title"]];
        NSLog(@"mesage.title = %@",message.title);
         message.description = [NSString stringWithFormat:@"%@",[dictResponse objectForKey:@"desc"]];
         NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[dictResponse objectForKey:@"imgUrl"]]]];
         message.thumbData = data;

         WXWebpageObject *ext = [WXWebpageObject object];
         ext.webpageUrl = [NSString stringWithFormat:@"%@",[dictResponse objectForKey:@"link"]];;

         message.mediaObject = ext;
         SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
         req.bText = NO;
         req.message = message;
         if (indexPath.row == 0) {
             req.scene = WXSceneTimeline;
             [WXApi sendReq:req];
         } else if (indexPath.row == 1) {
             req.scene = WXSceneSession;
             [WXApi sendReq:req];
         }

    } failure:^(NSError *error) {
        
    }];
}

#pragma mark 监听网络状态

- (void)checkNetworkState
{
     // 1.检测wifi状态
    Reachability *wifi = [Reachability reachabilityForLocalWiFi];
    
    // 2.检测手机是否能上网络(WIFI\3G\2.5G)
    Reachability *conn = [Reachability reachabilityForInternetConnection];
    
      // 3.判断网络状态
    if ([wifi currentReachabilityStatus] != NotReachable) { // 有wifi
          NSLog(@"有wifi");
        if (isconn==NO) {
            [self requestAds];
            [self initNewsData];
            isconn = YES;
        }
     } else if ([conn currentReachabilityStatus] != NotReachable) { // 没有使用wifi, 使用手机自带网络进行上网
           NSLog(@"使用手机自带网络进行上网");
         if (isconn==NO) {
             [self requestAds];
             [self initNewsData];
             isconn = YES;
         }
           } else { // 没有网络
               isconn = NO;
               NSLog(@"没有网络");
        }
}

#pragma mark 判断url类型广告

-(void)useNStringjudge:(NSString  *)strurl andTitle:(NSString *)title andactivity:(NSString *)ifactivity{
    
   BOOL isBol = [strurl hasPrefix:@"app-call"] == YES ?  YES : NO;
    if (isBol) {
        NSString *urlType = [[strurl componentsSeparatedByString:@"|"] lastObject];
        if (UserModel.password.length>1) {
            if ([urlType isEqualToString:@"1"]||[urlType isEqualToString:@"2"]) {//1食品安全小卫士
                ZCXActivityVC *vc= [[ZCXActivityVC alloc]init];
                vc.isCity = 2;
                vc.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:vc animated:YES];
            }else{
                [self usedWebViewController:@"3" andTitle:title];
            }
        }else{
            ZCLoginVC *login = [[ZCLoginVC alloc]init];
            login.hidesBottomBarWhenPushed = YES;
            login.isAd = @"1";
            [self.navigationController pushViewController:login animated:YES];
        }
    }else{
        [self usedWebViewController:strurl andTitle:title];
    }
}



#pragma mark 调用webView
-(void)usedWebViewController:(NSString *)url andTitle:(NSString *)title{
    
    if ([url isEqualToString:@"3"]) {
        url = [NSString stringWithFormat:@"%@/%@%@",[NetworkManager strURLBasic],@"index.php/M/Acsuzhou/like_product_list_app.html?mid=",UserModel.mid];
        NSLog(@"url === %@",url);
    }
    DZWebViewController *vc = [[DZWebViewController alloc] init];
    vc.strURL = url;
    vc.title = title;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark 导航栏
-(void)initnavegation{
    UIImageView *title_naImgaeView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 95, 20)];
    [title_naImgaeView setImage:[UIImage imageNamed:@"navigation_logo"]];
    self.navigationItem.titleView = title_naImgaeView;
    
    UIButton *getButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 60, 25)];
    getButton.titleLabel.font = [UIFont boldSystemFontOfSize:17];
    [getButton setTitle:@"提建议" forState:UIControlStateNormal];
    [getButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [getButton addTarget:self action:@selector(gotofeedBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:getButton];
    self.navigationItem.rightBarButtonItem = rightItem;
}

#pragma mark 反馈
-(void)gotofeedBack{
    ZCMeFeedbackVC *mefeed = [[ZCMeFeedbackVC alloc]init];
    [self.navigationController pushViewController:mefeed animated:YES];
}


@end
